<?php

namespace djepo\UserBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use djepo\UserBundle\Entity\Product;
use djepo\UserBundle\Entity\ProductAction;
use djepo\UserBundle\Entity\ProductExtended;
use djepo\UserBundle\Entity\Notification;
use djepo\UserBundle\Form\ProductType;

use Symfony\Component\HttpFoundation\Response;
use \DateTime;

/**
 * Product controller.
 *
 * @Route("/api/product")
 */
class ProductRestController extends Controller
{
    /**
     * Lists all Product entities.
     *
     * @Route("/", name="product")
     * @Method("GET")
     * @Template()
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();

        $entities = $em->getRepository('djepoUserBundle:Product')->findAll();

        $serializer = $this->get('serializer'); 

       return new Response($serializer->serialize($entities  , 'json')); 
    }

    /**
     * Get Product by Id
     *
     * @Route("/getbyid", name="getbyid")
     * @Method("POST")
     * @Template()
     */
    public function getbyidAction()
    {
        $em = $this->getDoctrine()->getManager();
        $userId = $this->get('request')->query->get('user');
        $user = $em->getRepository('djepoUserBundle:FosUser')->find($userId);

        $id = $this->get('request')->query->get('id');
        $pa = $em->getRepository('djepoUserBundle:ProductAction')->find($id);

        /*$id = $pa->getProduct()->getId();

        $qb = $em->createQueryBuilder();
        $qb->select('p');
        $qb->from('djepoUserBundle:ProductExtended','p');
        $qb->where('p.id = :id');
        $qb->setParameter('id',$id);*/
        $entity = $pa->getProduct();

        $qbA = $em->createQueryBuilder();
        $qbA->select('pa');
        $qbA->from('djepoUserBundle:ProductAction','pa');
        $qbA->where('pa.product = :product');
        $qbA->setParameter('product',$entity);
        $actions = $qbA->getQuery()->getResult();
        $nbrBonneAffaire = 0;
        $bonneaffaire = false;
        $nbrJelai = 0;
        $jelai = false;
        for ($j=0; $j < count($actions); $j++){
            if($actions[$j]->getAction() == 0){
                $nbrBonneAffaire++;
                if($actions[$j]->getUser()->getId() == $user->getId()) $bonneaffaire = true;
            }
            else{
                $nbrJelai++;
                if($actions[$j]->getUser()->getId() == $user->getId()) $jelai = true;
            }
        }
        $entity->bonneaffaire = $bonneaffaire;
        $entity->nbrbonneaffaire = $nbrBonneAffaire;
        $entity->jelai = $jelai;
        $entity->nbrjelai = $nbrJelai;

        $serializer = $this->get('serializer'); 

       return new Response($serializer->serialize($entity  , 'json')); 
    }

    /**
     * Get Stream of products
     *
     * @Route("/stream")
     * @Method("POST")
     * @Template()
     */
    public function streamAction()
    {
        $em = $this->getDoctrine()->getManager();
        $userId = $this->get('request')->query->get('user');
        $lastId = $this->get('request')->query->get('last');
        $user = $em->getRepository('djepoUserBundle:FosUser')->find($userId);
        $serializer = $this->get('serializer'); 

        $qb = $em->createQueryBuilder();
        $qb->select('u');
        $qb->from('djepoUserBundle:UserCategory','u');
        $qb->where('u.user = :user');
        $qb->setParameter('user',$user);
        $usercategory = $qb->getQuery()->getResult();
        $cats = array();
        foreach ($usercategory as $uc) 
            array_push($cats, $uc->getCategory()->getId());

        if($lastId == "new"){
            
            $qb = $em->createQueryBuilder();
            $qb->select('p');
            $qb->from('djepoUserBundle:ProductExtended','p');
            $qb->where('p.category IN ('.implode(",", $cats).')');
            //$qb->setParameter('usercategory',$usercategory);
            $qb->orderBy('p.id', 'DESC');
            $qb->setMaxResults(5);
            $entities = $qb->getQuery()->getResult();
            for ($i=0; $i < count($entities); $i++) { 
                $qbA = $em->createQueryBuilder();
    	        $qbA->select('pa');
    	        $qbA->from('djepoUserBundle:ProductAction','pa');
    	        $qbA->where('pa.product = :product');
            	$qbA->setParameter('product',$entities[$i]);
    	        $actions = $qbA->getQuery()->getResult();
    	        $nbrBonneAffaire = 0;
    	        $bonneaffaire = false;
    	        $nbrJelai = 0;
    	        $jelai = false;
    	        for ($j=0; $j < count($actions); $j++){
    	        	if($actions[$j]->getAction() == 0){
    	        		$nbrBonneAffaire++;
    	        		if($actions[$j]->getUser()->getId() == $user->getId()) $bonneaffaire = true;
    	        	}
    	        	else{
    	        		$nbrJelai++;
    	        		if($actions[$j]->getUser()->getId() == $user->getId()) $jelai = true;
    	        	}
    	        }
    	        $entities[$i]->bonneaffaire = $bonneaffaire;
    	        $entities[$i]->nbrbonneaffaire = $nbrBonneAffaire;
    	        $entities[$i]->jelai = $jelai;
    	        $entities[$i]->nbrjelai = $nbrJelai;
            }

            return new Response($serializer->serialize($entities , 'json')); 
        }
        else{
            $qb = $em->createQueryBuilder();
            $qb->select('p');
            $qb->from('djepoUserBundle:ProductExtended','p');
            $qb->where('p.category IN ('.implode(",", $cats).')');
            //$qb->setParameter('usercategory',$usercategory);
            $qb->orderBy('p.id', 'DESC');
            $qb->setMaxResults(1);
            $lastProduct = $qb->getQuery()->getSingleResult();
                $qb = $em->createQueryBuilder();
                $qb->select('p');
                $qb->from('djepoUserBundle:ProductExtended','p');
                $qb->where('p.category IN ('.implode(",", $cats).')');
                //$qb->setParameter('usercategory',$usercategory);
                $qb->orderBy('p.id', 'DESC');
                $qb->setMaxResults(5);
                $entities = $qb->getQuery()->getResult();
                for ($i=0; $i < count($entities); $i++) { 
                    $qbA = $em->createQueryBuilder();
                    $qbA->select('pa');
                    $qbA->from('djepoUserBundle:ProductAction','pa');
                    $qbA->where('pa.product = :product');
                    $qbA->setParameter('product',$entities[$i]);
                    $actions = $qbA->getQuery()->getResult();
                    $nbrBonneAffaire = 0;
                    $bonneaffaire = false;
                    $nbrJelai = 0;
                    $jelai = false;
                    for ($j=0; $j < count($actions); $j++){
                        if($actions[$j]->getAction() == 0){
                            $nbrBonneAffaire++;
                            if($actions[$j]->getUser()->getId() == $user->getId()) $bonneaffaire = true;
                        }
                        else{
                            $nbrJelai++;
                            if($actions[$j]->getUser()->getId() == $user->getId()) $jelai = true;
                        }
                    }
                    $entities[$i]->bonneaffaire = $bonneaffaire;
                    $entities[$i]->nbrbonneaffaire = $nbrBonneAffaire;
                    $entities[$i]->jelai = $jelai;
                    $entities[$i]->nbrjelai = $nbrJelai;
                }

                return new Response($serializer->serialize($entities  , 'json')); 
            
        }
        
        return new Response("error"); 
    }

    /**
     * Get Stream of products
     *
     * @Route("/streamload")
     * @Method("POST")
     * @Template()
     */
    public function streamloadAction()
    {
        $em = $this->getDoctrine()->getManager();
        $userId = $this->get('request')->query->get('user');
        $date = $this->get('request')->query->get('date');
        //$date_from = new DateTime($date);
        //$date_from = DateTime::createFromFormat("j-M-Y", $date);
        $date_from = $date;
        $user = $em->getRepository('djepoUserBundle:FosUser')->find($userId);
        $serializer = $this->get('serializer'); 

        $qb = $em->createQueryBuilder();
        $qb->select('u');
        $qb->from('djepoUserBundle:UserCategory','u');
        $qb->where('u.user = :user');
        $qb->setParameter('user',$user);
        $usercategory = $qb->getQuery()->getResult();
        $cats = array();
        foreach ($usercategory as $uc) 
            array_push($cats, $uc->getCategory()->getId());

        
        $qb = $em->createQueryBuilder();
        $qb->select('p');
        $qb->from('djepoUserBundle:ProductExtended','p');
        $qb->where('p.category IN ('.implode(",", $cats).')');
        $qb->andWhere($qb->expr()->lt('p.date', ':date_from'));
        $qb->setParameter('date_from',$date_from);
        $qb->orderBy('p.id', 'DESC');
        $qb->setMaxResults(5);
        $entities = $qb->getQuery()->getResult();
        for ($i=0; $i < count($entities); $i++) { 
            $qbA = $em->createQueryBuilder();
            $qbA->select('pa');
            $qbA->from('djepoUserBundle:ProductAction','pa');
            $qbA->where('pa.product = :product');
            $qbA->setParameter('product',$entities[$i]);
            $actions = $qbA->getQuery()->getResult();
            $nbrBonneAffaire = 0;
            $bonneaffaire = false;
            $nbrJelai = 0;
            $jelai = false;
            for ($j=0; $j < count($actions); $j++){
                if($actions[$j]->getAction() == 0){
                    $nbrBonneAffaire++;
                    if($actions[$j]->getUser()->getId() == $user->getId()) $bonneaffaire = true;
                }
                else{
                    $nbrJelai++;
                    if($actions[$j]->getUser()->getId() == $user->getId()) $jelai = true;
                }
            }
            $entities[$i]->bonneaffaire = $bonneaffaire;
            $entities[$i]->nbrbonneaffaire = $nbrBonneAffaire;
            $entities[$i]->jelai = $jelai;
            $entities[$i]->nbrjelai = $nbrJelai;
        }

        return new Response($serializer->serialize($entities  , 'json')); 
    }

    /**
     * Get Stream by Category
     *
     * @Route("/streamdiscover")
     * @Method("POST")
     * @Template()
     */
    public function streamdiscoverAction()
    {
        $em = $this->getDoctrine()->getManager();
        $offset = $this->get('request')->query->get('offset');
        $cat = $this->get('request')->query->get('cat');
        $userId = $this->get('request')->query->get('user');
        $category = $em->getRepository('djepoUserBundle:Category')->find($cat);
        $user = $em->getRepository('djepoUserBundle:FosUser')->find($userId);
        $serializer = $this->get('serializer'); 

        
        $qb = $em->createQueryBuilder();
        $qb->select('p');
        $qb->from('djepoUserBundle:ProductExtended','p');
        $qb->where('p.category = :cat');
        $qb->setParameter('cat',$category);
        $qb->orderBy('p.id', 'DESC');
        $qb->setFirstResult($offset);
        $qb->setMaxResults(5);
        $entities = $qb->getQuery()->getResult();
        for ($i=0; $i < count($entities); $i++) { 
            $qbA = $em->createQueryBuilder();
            $qbA->select('pa');
            $qbA->from('djepoUserBundle:ProductAction','pa');
            $qbA->where('pa.product = :product');
            $qbA->setParameter('product',$entities[$i]);
            $actions = $qbA->getQuery()->getResult();
            $nbrBonneAffaire = 0;
            $bonneaffaire = false;
            $nbrJelai = 0;
            $jelai = false;
            for ($j=0; $j < count($actions); $j++){
                if($actions[$j]->getAction() == 0){
                    $nbrBonneAffaire++;
                    $test = $user->getId();
                    if($actions[$j]->getUser()->getId() == $user->getId()) $bonneaffaire = true;
                }
                else{
                    $nbrJelai++;
                    if($actions[$j]->getUser()->getId() == $user->getId()) $jelai = true;
                }
            }
            $entities[$i]->bonneaffaire = $bonneaffaire;
            $entities[$i]->nbrbonneaffaire = $nbrBonneAffaire;
            $entities[$i]->jelai = $jelai;
            $entities[$i]->nbrjelai = $nbrJelai;
        }

        return new Response($serializer->serialize($entities  , 'json')); 
    }

    /**
     * Creates a new Product entity.
     *
     * @Route("/new")
     * @Method("POST")
     * @Template()
     */
    public function newAction(Request $request)
    {
        $jsonData = $this->get('request')->query->get('json');

        $serializer = $this->get('serializer');
        $product = $serializer->deserialize($jsonData, 'djepo\UserBundle\Entity\Product', 'json');

        $em = $this->getDoctrine()->getManager();
        $user = $em->getRepository('djepoUserBundle:FosUser')->find($product->getUser()->getId());
        $product->setUser($user);
        $category = $em->getRepository('djepoUserBundle:Category')->find($product->getCategory()->getId());
        $product->setCategory($category);
        $em->persist($product);
        $em->flush();
        $product->setDate(new \DateTime());

        return new Response($serializer->serialize($product  , 'json'));
        
    }

    /**
     * Uploads Product entity.
     *
     * @Route("/upload")
     * @Method("POST")
     * @Template()
     */
    public function uploadAction(Request $request)
    {
        $id = $this->get('request')->query->get('id');

        move_uploaded_file($_FILES["file"]["tmp_name"], "./upload/product-".$id.".jpg");

        return new Response('Product upload OK = '+ $id);
    }

    /**
     * Creates a new Product entity.
     *
     * @Route("/action")
     * @Method("POST")
     * @Template()
     */
    public function actionAction(Request $request)
    {
        $em = $this->getDoctrine()->getManager();
        $userId = $this->get('request')->query->get('user');
        $user = $em->getRepository('djepoUserBundle:FosUser')->find($userId);
        $productId = $this->get('request')->query->get('product');
        $product = $em->getRepository('djepoUserBundle:Product')->find($productId);
        $action = $this->get('request')->query->get('action');
        $price = $this->get('request')->query->get('price');
        $flag = $this->get('request')->query->get('flag');
        if($flag == "true"){
            $pAction = new ProductAction();
            $pAction->setUser($user);
            $pAction->setProduct($product);
            $pAction->setAction($action);
            if($price) $pAction->setPrice($price);
            $em->persist($pAction); 
            $em->flush();
            // Add notification
            $notification = new Notification();
            $notification->setUser($product->getUser());
            $notification->setNotification("like");
            $notification->setObject("product_action_".$pAction->getAction());
            $notification->setObjectId($pAction->getId());
            $notification->setView(false);
            $em->persist($notification);
            $em->flush();
        }
        else{
            $qb = $em->createQueryBuilder();
            $qb->select('pa');
            $qb->from('djepoUserBundle:ProductAction','pa');
            $qb->where('pa.user = :user');
            $qb->setParameter('user',$user);
            $qb->andWhere('pa.action = :action');
            $qb->setParameter('action',$action);
            $qb->andWhere('pa.product = :product');
            $qb->setParameter('product',$product);
            $pAction = $qb->getQuery()->getSingleResult();
            
            $qb = $em->createQueryBuilder();
            $qb->select('n');
            $qb->from('djepoUserBundle:Notification','n');
            $qb->where('n.objectId = :objectId');
            $qb->setParameter('objectId',$pAction->getId());
            $qb->andWhere('n.object = :object');
            $qb->setParameter('object',"product_action_".$pAction->getAction());
            $notification = $qb->getQuery()->getSingleResult();
            $em->remove($notification);
            $em->remove($pAction);
            $em->flush();

        }
        
        return new Response("OK");
    }

    /**
     * Get Product Prices.
     *
     * @Route("/price")
     * @Method("POST")
     * @Template()
     */
    public function priceAction(Request $request)
    {
        $id = $this->get('request')->query->get('id');

        $em = $this->getDoctrine()->getManager();

        $qb = $em->createQueryBuilder();
        $qb->select('p');
        $qb->from('djepoUserBundle:ProductAction','p');
        $qb->where('p.product = :id');
        $qb->setParameter('id',$id);
        $qb->andWhere('p.price IS NOT NULL');
        $qb->orderBy('p.id', 'DESC');
        $entities = $qb->getQuery()->getResult();

        $serializer = $this->get('serializer');

        return new Response($serializer->serialize($entities  , 'json'));
    }
    
}